<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
        <title></title>
        <!-- 引入 WeUI -->
        <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/1.1.2/weui.min.css"/>
        <link rel="stylesheet" href="//cdn.bootcss.com/jquery-weui/1.0.1/css/jquery-weui.min.css">
        
        <style type="text/css">
            body{
                height: 100%;
            }
            .container, .page {
                position: absolute;
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
            }
            .hidden{
                display: none;
            }
            .number-password{

            }
        </style>
    </head>
    <body >
    <!-- loading toast -->
    <div id="loadingToast" style="display: none;">
        <div class="weui-mask_transparent"></div>
        <div class="weui-toast" style="visibility:visible;opacity: 100">
            <i class="weui-loading weui-icon_toast"></i>
            <p class="weui-toast__content">数据加载中</p>
        </div>
    </div>
            <div class="container" id="container">
                    <div class="page tabbar js_show">
                        <div class="page__bd" style="position:relative;height: 100%;">
                            <div class="weui-tab" >
                                <div class="weui-tab__panel">
                                  <div id="bindDeviceD">
                                      <div class="weui-cells__title" style="text-align:center">设备绑定</div>
                                      <div class="weui-cells weui-cells_form">
                                        <div class="weui-cell">
                                            <div class="weui-cell__hd"><label class="weui-label">设备名称</label></div>
                                            <div class="weui-cell__bd">
                                                <input class="weui-input" id="deviceName"  placeholder="自定义设备名称"/>
                                            </div>
                                        </div>
                                        <div class="weui-cell weui-cell_vcode">
                                            <div class="weui-cell__hd">
                                                <label class="weui-label">智能锁编号</label>
                                            </div>
                                            <div class="weui-cell__bd">
                                                <input class="weui-input" id="deviceId" placeholder="设备编号"/>
                                            </div>
                                            <div  class="weui-cell__ft">
                                                <button id="lockScanBT" class="weui-vcode-btn hidden">扫码</button>
                                                <button id="lockUnbindBT" class="weui-vcode-btn hidden">解绑</button>
                                            </div>
                                        </div>
                                          <div id="passwordDiv" class="weui-cell hidden">
                                              <div class="weui-cell__hd"><label class="weui-label">开锁密码</label></div>
                                              <div class="weui-cell__bd">
                                                  <input class="weui-input number-password" type="password" pattern="[0-9]*" inputmode="numeric" id="password"  maxlength="6" placeholder="6位数字"/>
                                              </div>
                                          </div>
                                          <div id="repeatPasswordDiv" class="weui-cell hidden">
                                              <div class="weui-cell__hd"><label class="weui-label">重复密码</label></div>
                                              <div class="weui-cell__bd">
                                                  <input class="weui-input number-password" type="password" pattern="[0-9]*" inputmode="numeric" id="repeatPassword" maxlength="6"  placeholder="6位数字"/>
                                              </div>
                                          </div>


                                          <div class="weui-cell weui-cell_vcode">
                                              <div class="weui-cell__hd">
                                                  <label class="weui-label">摄像头编号</label>
                                              </div>
                                              <div class="weui-cell__bd">
                                                  <input class="weui-input" id="cameraId" placeholder="设备编号"/>
                                              </div>
                                              <div  class="weui-cell__ft">
                                                  <button id="cameraScanBT" class="weui-vcode-btn hidden">扫码</button>
                                                  <button id="cameraUnbindBT" class="weui-vcode-btn hidden">解绑</button>
                                              </div>
                                          </div>
                                      </div>
                                      <div class="weui-btn-area">
                                          <a id="submitDeviceA" class="weui-btn weui-btn_primary" href="javascript:">确定</a>
                                          <a id="sendWarningMessageA" class="weui-btn weui-btn_warn" href="javascript:">发送报警测试</a>
                                      </div>
                                  </div>
                                </div>
                            </div>
                            <div class="weui-tabbar" style="z-index:5;">
                              <a href="../deviceInfo" class="weui-tabbar__item" data-tab="firstTab">
                                  <span style="display: inline-block;position: relative;">
                                      <img src="./images/icon_tabbar.png" alt="" class="weui-tabbar__icon"/>
                                      <!--<span class="weui-badge" style="position: absolute;top: -2px;right: -13px;">8</span>-->
                                  </span>
                                  <p class="weui-tabbar__label">设备信息</p>
                              </a>
                              <a href="../deviceEvent" class="weui-tabbar__item" data-tab="secondTab">
                                  <img src="./images/icon_tabbar.png" alt="" class="weui-tabbar__icon"/>
                                  <p class="weui-tabbar__label">设备事件</p>
                              </a>
                                <a href="../deviceManage" class="weui-tabbar__item  weui-bar__item_on" data-tab="thirdTab">
                                    <img src="./images/icon_tabbar.png" alt="" class="weui-tabbar__icon"/>
                                    <p class="weui-tabbar__label">设备维护</p>
                                </a>
                                <a href="../remoteOpenDoor" class="weui-tabbar__item" data-tab="fourthTab">
                                    <img src="./images/icon_tabbar.png" alt="" class="weui-tabbar__icon"/>
                                    <p class="weui-tabbar__label">远程开锁</p>
                                </a>
                            </div>
                            </div>
                        </div>
                    </div>
                </div>
   </body>
   
    <script src="//cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
    <script src="//res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    <script src="//cdn.bootcss.com/jquery-weui/1.0.1/js/jquery-weui.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){

          // 限制只能输入数字
          $('.number-password').keypress(function(key) {
              if(key.charCode < 48 || key.charCode > 57) return false;
          });


          //获取jsTicket
          function getJsTicket(){
              $.ajax({
                  type: "POST",
                  url: "/getJsTicketSignuature",
                  contentType: "application/json; charset=utf-8",
                  data: JSON.stringify({"url":location.href}),
                  dataType: "json",
                  success: function (data) {
                      console.log(data);
                      wx.config({
                          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                          appId: data.appId, // 必填，公众号的唯一标识
                          timestamp: data.timestamp, // 必填，生成签名的时间戳
                          nonceStr: data.noncestr, // 必填，生成签名的随机串
                          signature: data.signature,// 必填，签名，见附录1
                          jsApiList: ['scanQRCode'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                      });
                  },
                  error: function (message) {
                      $("#request-process-patent").html("提交数据失败！");
                  }
              });
          }
          getJsTicket();
          var mydevice = null;
          //获取我的设备
          function getMyDevice(){
              //2 查出数据
              $.ajax({
                  type: "get",
                  url: "/myDevice",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function (data) {
                      if (data.success == "true") {
                          var device = data.data;
                          mydevice = device;
                          if (device != null) {
                              if (device.cameraId != null && device.cameraId != "") {
                                  $("#cameraScanBT").hide();
                                  $("#cameraUnbindBT").show();
                                  $("#cameraId").val(device.cameraId);
                                  $("#cameraId").attr("disabled", true);
                              } else {
                                  $("#cameraScanBT").show();
                                  $("#cameraUnbindBT").hide();
                              }
                              if (device.deviceId != null && device.deviceId != "") {
                                  $("#lockScanBT").hide();
                                  $("#lockUnbindBT").show();
                                  $("#deviceId").val(device.deviceId);
                                  $("#deviceId").attr("disabled", true);
                                  //隐藏开锁密码文本框
                                  $("#repeatPasswordDiv").addClass("hidden");
                                  $("#passwordDiv").addClass("hidden");
                              } else {
                                  $("#lockScanBT").show();
                                  $("#lockUnbindBT").hide();
                                  //显示开锁密码文本框
                                  $("#repeatPasswordDiv").removeClass("hidden");
                                  $("#passwordDiv").removeClass("hidden");
                              }
//                              if (device.cameraId != null && device.cameraId != "" && device.deviceId != null && device.deviceId != ""){
//                                  $("#submitDeviceA").hide();
//                              }
                              $("#deviceName").val(device.name);
                          } else {
                              $("#cameraScanBT").show();
                              $("#lockScanBT").show();
                              $("#cameraUnbindBT").hide();
                              $("#lockUnbindBT").hide();
                              //显示设置开锁密码文本框
                              $("#repeatPasswordDiv").removeClass("hidden");
                              $("#passwordDiv").removeClass("hidden");
                          }
                      }
                  },
                  error: function (XMLHttpRequest, textStatus, errorThrown) {
                  }
              });
          }
          getMyDevice();

          wx.ready(function(){
              // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
          });

          wx.error(function(res){
              // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
              console.log(res);
          });

          //设备绑定提交
         $("#submitDeviceA").on('click',function(){
            //绑定设备到用户
            var deviceId =$("#deviceId").val();
            var cameraId =$("#cameraId").val();
            var deviceName = $("#deviceName").val();
            if (deviceId == "" || deviceName == "") {
                $.toast("请输入设备信息", "forbidden");
                return;
            }
             //y用户第一次绑定智能锁，所以需要校验密码是否符合规范
             if (mydevice == null || mydevice.deviceId == null ||mydevice.deviceId == '') {
                var passwordVal = $("#password").val();
                var repeatPasswordVal = $("#repeatPassword").val();
                if (passwordVal != repeatPasswordVal) {
                    $.toast("两次密码不匹配", "forbidden");
                    return;
                }

                 if (passwordVal.length != 6) {
                     $.toast("密码须是6位数字", "forbidden");
                     return;
                 }
             }
            $("#submitDeviceA").attr("disabled",true);
            var $loadingToast = $("#loadingToast");
            if ($loadingToast.css('display') != 'none') return;
            $loadingToast.fadeIn(100);
            $.ajax({
                type: "POST",
                url: "/bindDeviceToUser",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({"deviceId":deviceId, "name":deviceName, "cameraId":cameraId, "password":$("#password").val()}),
                dataType: "json",
                success: function (data) {
                    $.toast("设备绑定成功");
                    window.location.reload();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var responseData = JSON.parse(XMLHttpRequest.responseText);
                    $.toast(responseData.exceptionObj.message,"text")
                },
                complete: function(){
                    $loadingToast.fadeOut(100);
                }
            });
        })

          //演示报警事件.
          $("#sendWarningMessageA").on('click',function(){
              $.ajax({
                  type: "GET",
                  url: "/warning",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function (data) {
                      $.toast("发送成功");
                  },
                  error: function (XMLHttpRequest, textStatus, errorThrown) {
                      $.toast("发送失败")
                  },
                  complete: function(){
                  }
              });
          })


          //摄像头的编号扫描, 扫描成功后，截取前半部分作为设备编号
          $("#cameraScanBT").on('click', function () {
              console.log("开始摄像头扫码");
              wx.scanQRCode({
                  needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                  scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                  success: function (res) {
                      var result = res.resultStr;
                      var dianxinCameraIndex = result.indexOf("|");
                      var wulianCameraIndex =  result.indexOf("cmic");//物联的摄像头编号是cmic打头
                      if (dianxinCameraIndex > 0 ){
                          var result = result.substr(0, dianxinCameraIndex); // 当needResult 为 1 时，扫码返回的结果
                          $("#cameraId").val(result);
                      } else if  (wulianCameraIndex > -1 ){
                          var result = result.substr(4);
                          $("#cameraId").val(result);
                      } else {
                          $.toast("编号格式错误");
                      }

                  }
              });
          });
          //摄像头的解绑
          $("#cameraUnbindBT").on('click', function () {
              unBindeDevice("camera");
          });

          //智能锁的编号扫描
          $('#lockScanBT').on('click', function () {
              console.log("开始扫码");
              wx.scanQRCode({
                  needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                  scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                  success: function (res) {
                      try{
                          var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                          var lockId = result.split(";")[2].split(":")[1];
                          $("#deviceId").val(lockId);
                      } catch (exception) {
                          $.toast("编号格式错误");
                      }
                  }

              });
          });
          //智能锁的解绑
          $("#lockUnbindBT").on('click', function () {
              unBindeDevice("lock");
          });

          //解绑设备(包括智能锁和摄像头)
          function unBindeDevice(type){
              var url = "";
              var deviceName = "";
              var data = null;
              if (type == 'lock') {
                  url = "/unBindLock"
                  $.prompt({
                      title: '解绑智能锁',
                      text: '请输入6位数字密码',
                      input: '',
                      empty: false, // 是否允许为空
                      onOK: function (input) {
                          //点击确认
                          data = {"deviceId": $("#deviceId").val(), "password": input}
                          doUnbind(data, 'lock');
                      },
                      onCancel: function () {
                          //点击取消
                      }
                  });

              } else if (type == 'camera') {
                  url = "/unBindCamera"
                  deviceName = "摄像头";
                  data = {"cameraId": $("#cameraId").val()}
                  $.confirm("确定解绑" + deviceName, function() {
                      //点击确认后的回调函数
                      doUnbind(data, 'camera');

                  }, function() {
                      //点击取消后的回调函数
                  });
              }
          }

            //执行解绑。
          function doUnbind(data, type) {
              var url = null;
              if (type == 'lock') {
                  url = "/unBindLock"
              } else if (type == 'camera') {
                  url = "/unBindCamera"
              }
              $.ajax({
                  type: "post",
                  url: url,
                  contentType: "application/json; charset=utf-8",
                  data:JSON.stringify(data),
                  dataType: "json",
                  success: function (data) {
                      if (data.success == "true") {
                          $.toast("设备解绑成功");
                      }
                      window.location.reload();
                  },
                  error: function (XMLHttpRequest, textStatus, errorThrown) {
                      var responseData = JSON.parse(XMLHttpRequest.responseText);
                      $.toast(responseData.exceptionObj.message);
                  },
                  complete: function(){

                  }
              });
          }

      });
    </script>
</html>
